package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	GenInt64Id "lot_admin_api/utility/genInt64IdOfString"
	"lot_admin_api/utility/response"
)

type sEquipmentPort struct{}

var insEquipmentPort = sEquipmentPort{}

func EquipmentPort() *sEquipmentPort {
	return &insEquipmentPort
}

// AddEquipment 批量新增设备端口
func (s *sEquipmentPort) AddEquipment(ctx context.Context, req *model.BatchAddEquipmentPortReq) (lastInsertId string, err error) {
	r := g.RequestFromCtx(ctx)
	// 按照传过来的端口号 在设备端口表里面存如对应的端口信息
	printPropList := make([]*model.EquipmentPortIdAndInfoRes, 0)
	for i := 0; i < req.PortNum; i++ {
		var printPropInfo *model.EquipmentPortIdAndInfoRes
		propInfo := g.Map{
			"Id":         GenInt64Id.GenInt64IdOfString(), // 端口的id
			"EqId":       req.EqId,                        // 设备号
			"PortCode":   i + 1,                           // 端口号
			"PortStatus": 0,                               // 状态
		}
		_ = gconv.Scan(propInfo, &printPropInfo)
		printPropList = append(printPropList, printPropInfo)
	}
	if _, err = dao.LotEquipmentPort.Ctx(ctx).FieldsEx("start_time").Save(printPropList); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "保存设备端口失败")
	}
	return lastInsertId, err
}

// EditEquipmentPortStatus 修改设备端口的状态
func (s *sEquipmentPort) EditEquipmentPortStatus(ctx context.Context, req *model.EditEquipmentPortStatus) (lastInsertId string, err error) {
	r := g.RequestFromCtx(ctx)
	portUpdate := g.Map{
		"port_status": req.PortStatus,
	}
	if _, err = dao.LotEquipmentPort.Ctx(ctx).Where("id", req.Id).Update(&portUpdate); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	return req.Id, err
}
